import type {ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import {Button, message, Popconfirm, Switch} from "antd";
import Collection from './components/collectionRecord'
import {PlusOutlined} from "@ant-design/icons";
import {useRef, useState} from "react";
import Create from "./components/create";
import {copyCoupon, couponList, delCoupon, getUpList} from "@/services/ant-design-pro/marketing";


export default () => {
  //  添加及修改优惠券 modal 状态
  const [modalCoupon,setModalCoupon] = useState(false)
  //  领取记录 modal 状态
  const [collectionRecord,setCollectionRecord] = useState(false)
  //  定义领取记录要获取的ID
  const [recordId,setRecordId] = useState(null)
  //  定义领取记录索要获取到的数据
  const [records,setRecords] = useState([])
  //  刷新表单
  const actionRef = useRef<ActionType>();

  const columns = [
    {
      dataIndex: 'id',
      width: 100,
      title: 'ID',
      search: false,
      align: 'center',
    },
    {
      title: '优惠券名称',
      dataIndex: 'title',
      align: 'center',
      width: 200,
    },
    {
      title: '优惠券类型',
      dataIndex: 'type',
      align: 'center',
      search: false,
      valueType: 'select',
      valueEnum: {
        receives_one: '通用券',
        receives_two: '品类券',
        receives_three: '商品券'
      }
    },
    {
      title: '面值',
      dataIndex: 'coupon_price',
      search: false,
      align: 'center',

    },
    {
      title: '领取方式',
      dataIndex: 'receive_type',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        receive_one: '手动领取',
        receive_two: '新人券',
        receive_three: '赠送券',
        receive_four: '会员券'
      }
    },
    {
      title: '领取日期',
      dataIndex: 'collection_date',
      search: false,
      align: 'center',

    },
    {
      title: '使用时间',
      dataIndex: 'date_of_use',
      search: false,
      align: 'center',
    },
    {
      title: '发布数量',
      dataIndex: 'num',
      search: false,
      align: 'center',
      render(_,record){
        if (record.num.type === 1){
          return (
            <div>
              <div>
                {record.num.release.title}:{record.num.release.num}
              </div>
              <div style={{color: 'red'}}>
                {record.num.surplus.title}:{record.num.surplus.num}
              </div>
            </div>
          )
        }
        return <div>{record.num.unlimited.title}</div>
      }

    },
    {
      title: '是否有效',
      dataIndex: 'status',
      align: 'center',
      filters: true,
      onFilter: true,
      search: false,
      valueType: 'select',
      render: (_,record) => [
        <Switch
          checkedChildren="开启"
          unCheckedChildren="关闭"
          defaultChecked={record.status}
          onChange={async (state) => {
            getUpList(record.id,{
              status:state ? 1 : 0,
            }).then(() => {
              message.success('操作成功！')
              actionRef.current?.reload();
            })
          }}
        />
      ]
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      width: 200,
      render: (_, record) => [
        <a
          onClick={() => {
            //  改变领取记录 modal 状态
            setCollectionRecord(true)
            //  获取到单条的ID
            setRecordId(record.id)
          }}
        >
          领取记录
        </a>,
        <a
          onClick={async ()=>{
            const copyLists = await copyCoupon(record.id)
            console.log(copyLists)
            setRecords(copyLists)
            setModalCoupon(true);
          }}
        > 复制 </a>,
        <Popconfirm
          title="确定要删除发布的优惠券吗？"
          onConfirm={()=>{
            delCoupon(record.id).then(()=>{
              message.success('删除成功');
              actionRef.current.reload();
            })
          }}
          onCancel={()=>{
            message.success('已取消');
          }}
          okText="确定"
          cancelText="取消"
        >
          <a href="#">删除</a>
        </Popconfirm>
      ],
    },
  ];
  // 定义添加优惠劵 modal 确定所传回来的数据及状态
  const submit = () => {
    setModalCoupon(false)
    //  是否更改刷新表单
    actionRef.current?.reload()
  }

  return (
    <PageContainer
      header={{
        breadcrumb: {},
      }}
    >
    <ProTable
      columns={columns}
      actionRef={actionRef}
      request={async (params)=>{
        const {data,meta} =  await couponList({...params})
        return{
          data,
          success:true,
          total:meta.pagination.total
        }
      }}
      editable={{
        type: 'multiple',
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      scroll={{ x: 1800 }}
      form={{
        // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 10,
      }}
      dateFormatter="string"
      toolBarRender={() => [
        <Button
          type="primary"
          onClick={() => {
            setRecords([])
            setModalCoupon(true);
          }}
          icon={<PlusOutlined />}
        >
          添加优惠券
        </Button>
      ]}
    />
      {/* 添加及修改优惠劵的 modal */}
      {modalCoupon ?
        <Create
          isModalCoupon={modalCoupon}
          couponOk={submit}
          couponCoup={records}
          handleCancel={()=>{
            setModalCoupon(false)
        }}
      />:null}

      {
        collectionRecord ?
          <Collection
            id={recordId}
            isCollectionVisit={collectionRecord}
            collectionCancel={()=>{
              setCollectionRecord(false)
            }}
          /> : null
      }

    </PageContainer>

  );
};
